package local.eken.gfx.core;

import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;

import javax.swing.JFrame;

import local.eken.gfx.core.impl.IHandleView;
import local.eken.gfx.states.ExitView;
import local.eken.gfx.states.GameView;
import local.eken.gfx.states.MenuView;
import local.eken.gfx.states.impl.ViewState;
import local.eken.misc.GamePreferences;

public class MainWindow extends JFrame implements IHandleView {
	private static final long serialVersionUID = -3114471099248417020L;
	
	private static final int EXIT_VIEW = 0;
	private static final int MENU_VIEW = 1;
	private static final int GAME_VIEW = 2;
	
	private final ViewState[] states = {new ExitView(this), new MenuView(this), new GameView(this)};
	private int currentState = MENU_VIEW;
	
	public MainWindow() {
		this.init();
		this.initComponent();
		this.setVisible(true);
	}
	
	private void init() {
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setResizable(false);
		
		GamePreferences prefs = GamePreferences.getInstance();
		
		if(prefs.isFullscreen()) {
			if(prefs.isWindowMode()) {
				Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
				this.setBounds(0, 0, d.width, d.height);
				this.setPreferredSize(d);
			} else {
				GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
				try {
					if(gd.isFullScreenSupported()) {
						gd.setFullScreenWindow(this);
					}
				} finally {
					gd.setFullScreenWindow(null);
				}
			}
		} else {
			this.setPreferredSize(prefs.getResolution());
		}
		
		this.add(this.states[this.currentState]);
	}

	private void exit() {
		this.dispose();
		System.exit(0);
	}
	
	@Override
	public void prevState() {
		if(this.currentState == EXIT_VIEW) {
			this.exit();
		}
		
		this.remove(this.states[this.currentState]);
		this.currentState--;
		
		this.add(this.states[this.currentState]);
		this.states[this.currentState].revalidate();
	}

	@Override
	public void nextState() {
		if(this.currentState == GAME_VIEW) {
			return;
		}
		
		this.currentState++;
	}
	
	private void initComponent() {
		this.pack();
		this.repaint();
	}
}
